package handel

import (
	"car-order/cache"
	"car-order/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func CarAdd(c *gin.Context) {
	car_name := c.PostForm("car_name")
	data := model.Car{
		CarName: car_name,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func Order(c *gin.Context) {
	order_num, _ := strconv.Atoi(c.PostForm("order_num"))
	order_price, _ := strconv.Atoi(c.PostForm("order_price"))
	car_id, _ := strconv.Atoi(c.PostForm("car_id"))
	data := model.Order{
		OrderNum:   order_num,
		OrderPrice: order_price,
		CarID:      car_id,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}
func OrderList(c *gin.Context) {
	/*
			SELECT
		  cars.car_name AS CarName,
		  orders.order_num AS OrderNum,
		  orders.order_price AS OrderPrice
		FROM
		  orders
		  LEFT JOIN cars ON orders.car_id = cars.id
	*/
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	var list []model.List
	redis_key := "order_list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("orders").
			Select(
				"cars.car_name AS CarName",
				"orders.order_num AS OrderNum",
				"orders.order_price AS OrderPrice",
			).
			Joins("LEFT JOIN cars ON orders.car_id = cars.id").
			Offset(offset).Limit(size).
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	var total int64
	model.DB.Model(&model.Order{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "展示成功",
		"data":  list,
		"total": total,
	})
}
func OrderFind(c *gin.Context) {
	id := c.Query("id")
	var list model.List
	redis_key := "order_find_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("orders").
			Select(
				"cars.car_name AS CarName",
				"orders.order_num AS OrderNum",
				"orders.order_price AS OrderPrice",
			).
			Joins("LEFT JOIN cars ON orders.car_id = cars.id").
			Where("orders.car_id=?", id).
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": list,
	})
	return
}
